package com.zsk.shop.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.base.NoMsgException;
import com.zsk.shop.common.enums.SmsEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * Created by yuwenbo on 2019/3/30 14:09.
 */
@Slf4j
@Component
public class SmsUtil {

    @Autowired
    private DingTalkRootUtil dingTalkRootUtil;

    @Autowired
    private Environment environment;

    /**
     * 发送短信
     *
     * @param phone
     * @return
     */
    public BaseResponse send(String phone, String templateCode, JSONObject jsonObject) {
        String accessKeyId = environment.getProperty("ali.smsRAM.accessKeyId");
        String accessKeySecret = environment.getProperty("ali.smsRAM.accessKeySecret");
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", SmsEnum.sign);
//        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", jsonObject.toJSONString());
        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject object = JSONObject.parseObject(response.getData());
            log.info("短信通道反馈:" + object);
            if (object.get("Code").equals("OK")) {
                dingTalkRootUtil.sendSmsInfo(phone, templateCode, jsonObject.get("code").toString(), true, object);
                return BaseResponse.success("短信发送成功");
            } else {
                dingTalkRootUtil.sendSmsInfo(phone, templateCode, jsonObject.get("code").toString(), false, object);
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (NoMsgException e) {
            e.printStackTrace();
            return BaseResponse.error("发送短信失败" + e.getErrorMessage());
        }
        return BaseResponse.error("短信服务商发送短信失败");
    }
}
